package com.example.serenity.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.serenity.controller.model.Query;
import com.example.serenity.controller.model.Response;
import com.example.serenity.dao.MessageMapper;
import com.example.serenity.entity.Message;
import com.example.serenity.service.MessageService;
import com.example.serenity.util.MyUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/message")
public class MessageController {
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private MessageService messageService;

    @GetMapping("/type")
    public Response<?> type(){
        return new Response<>(messageMapper.getLabels());
    }

    @GetMapping("/delete")
    public Response<?> delete(@RequestParam("id")Integer id){
        Message message = messageMapper.selectById(id);
        if(MyUtil.computationTime(message.getTime(), new Date()) > 60L){
            return new Response<>("0", "胶水已经干啦~");
        }
        messageMapper.deleteById(id);
        return new Response<>("删除成功！");
    }

    @GetMapping("/one")
    public Response<?> one(@RequestParam("id")Integer id){
        return new Response<>(messageMapper.getOne(id));
    }

    @GetMapping("/like")
    public Response<?> like(@RequestParam("id")Integer id){
        messageMapper.like(id);
        return new Response<>("点赞成功");
    }

    @PostMapping("/list")
    public Response<?> list(Query query){
        return new Response<>(messageService.getList(query));
    }

    @PostMapping("/post")
    public Response<?> post(Message message, HttpServletRequest request){
        if(message.getColor()==null||message.getContent()==null||message.getName()==null){
            return new Response<>("0","信息不完整");
        }
        try {
            String ip = MyUtil.getRemoteHost(request);
            String url = "https://apis.map.qq.com/ws/location/v1/ip?key=IHXBZ-M5PKJ-ACIF4-FBBQ5-M3QKZ-QJFKP&ip="+ip;
            JSONObject json = JSONUtil.parseObj(MyUtil.doGetAsStr(url));
            if(json.getStr("message").equals("Success")){
                JSONObject result = json.getJSONObject("result");
                JSONObject info = result.getJSONObject("ad_info");
                message.setAddress(info.getStr("province")+" "+info.getStr("city"));
            }
            else  message.setAddress("未知");
        } catch (Exception e) {
            e.printStackTrace();
            message.setAddress("未知");
        }
        message.setTime(new Date());
        if(message.getUrl()==null||message.getMinUrl()==null) message.setType("text");
        else message.setType("image");
        messageMapper.insert(message);
        return new Response<>("留言成功啦~");
    }
}
